package top.lixunda.common.validate.validate;

import top.lixunda.common.validate.annotation.XumDateFormat;
import top.lixunda.common.validate.core.ValidateError;
import top.lixunda.common.validate.exception.XumValidException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.regex.Pattern;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 */
public class DateFormatValidate implements AnnotationValidate {

    @Override
    public boolean support(Class annotationClass) {
        return XumDateFormat.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        XumDateFormat a = (XumDateFormat) annotation;
        boolean isNull = (value == null || (value instanceof String && "".equals(value)));
        if (isNull) {
            return null;
        }
        if (a.value().length == 0 || a.value().length > 2) {
            throw new XumValidException("XumDateFormat value值长度必须大于0小于3");
        }
        String regex = "^" + a.startWith() + "([0-9]{4})" +
                a.value()[0] + "((0[1-9])|(1[0-2]))" + (a.value().length == 2 ? a.value()[1] : a.value()[0]) +
                "((0[1-9])|([1-2][0-9])|(3[0-1]))" + a.endWith() + "$";
        return Pattern.matches(regex, value.toString()) ? null :
                new ValidateError(getErrorMessage(a.message(), field, value));
    }

    private String getErrorMessage(String message, Field field, Object value) {
        return "".equals(message)
                ? field.getName() + "不符合要求的日期格式"
                : message.replaceAll("#value#", String.valueOf(value)).replaceAll("#name#", field.getName());
    }

}
